package com.ittony.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ittony.health.domain.SetMeal;
import com.ittony.health.entity.PageResult;
import com.ittony.health.entity.QueryPageBean;
import com.ittony.health.mapper.CheckGroupMapper;
import com.ittony.health.mapper.SetMealMapper;
import com.ittony.health.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<SetMeal> pageSetMeal = setMealMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(pageSetMeal.getTotal(), pageSetMeal.getResult());
    }

    @Override
    public SetMeal findById(Integer id) {
        return setMealMapper.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetMealId(Integer setMealId) {
        return setMealMapper.findCheckGroupIdsBySetMealId(setMealId);
    }

    @Override
    public void add(Integer[] checkGroupIds,SetMeal setMeal) {
        setMealMapper.add(setMeal);
        if(checkGroupIds != null && checkGroupIds.length > 0) {
            Integer setMealId = setMeal.getId();
            setMealMapper.addSetMealCheckGroup(setMealId,checkGroupIds);
        }
    }

    @Override
    public void delete(Integer id) {
        List<Integer> checkGroupIds = checkGroupMapper.getIdsBySetMealId(id);
        if(checkGroupIds == null || checkGroupIds.isEmpty()) {
            setMealMapper.delete(id);
        } else {
            throw new RuntimeException("存在已关联至本套餐的检查组");
        }
    }

    @Override
    public void edit(Integer[] checkGroupIds, SetMeal setMeal) {
        setMealMapper.update(setMeal);
        Integer setMealId = setMeal.getId();
        setMealMapper.deleteSetMealCheckGroups(setMealId);
        if(checkGroupIds != null && checkGroupIds.length > 0) {
            setMealMapper.addSetMealCheckGroup(setMealId,checkGroupIds);
        }
    }
}
